//
//  MDHSwiftExtension.swift
//  JSTech
//
//  Created by 高得华 on 2019/9/27.
//  Copyright © 2020 华&梅. All rights reserved.
//  拓展文件

import UIKit


///真机 or 模拟器判断
struct MDHPlatform {
    static let isSimulator: Bool = {
        var isSim = false
        #if arch(i386) || arch(x86_64)
            isSim = true
        #endif
        return isSim
    }()
}


class MDHSwiftExtension: NSObject { }

//MARK: - ===== MDHSwiftHeader === -
extension MDHSwiftHeader {
    
    ///活动 弹窗
    @objc class func showActiveAlertVc() -> () {
        
    }
    
    ///拉黑 的提示
    @objc class func v1_message_addBlack(userId: Int) -> () {
        ///加入黑名单
        let message = "拉黑后将不会收到对方消息，请在\n“我的-设置-黑名单”中解除，\n是否确定？"
        AlertViewShowTR("提示", message, "确定", { (index1) in
            MDHFileConstant.mainAsyncSafe({
                if index1 == 2 {
                }
            })
        })
    }
    
    /*///创建、获取本地SVGA文件视图 播放声音的动效
    @objc class func setup_SVGAPlayer(name: String) -> SVGAPlayer {
        let sa = SVGAPlayer()
        //sa.backgroundColor = UIColor.red
        sa.isUserInteractionEnabled = false///不能点击
        sa.loops = 0///播放次数 0代表无限播放
        
        ///大礼物的刷 刷 刷展示动画
        let sa_p = SVGAParser()
        sa_p.enabledMemoryCache = true
        sa_p.parse(withNamed: name, in: nil, completionBlock: { (videoItem) in
            sa.videoItem = videoItem
            sa.startAnimation()
        }) { (error) in
            print(error)
        }
        return sa
    }*/
    
    ///创建 统一的 视图 第一层的Segment
    @objc class func viewCategoryTitle() -> JXCategoryTitleView {
        let scale = kMDHPTAutoScale()
        let vi = JXCategoryTitleView()
        vi.defaultSelectedIndex = 0
        vi.titleSelectedColor = kColor_MDH333333()
        vi.titleColor = kColor_MDH333333()
        ///不平分宽度
        vi.isAverageCellSpacingEnabled = false
        ///是否渐变过渡
        vi.isTitleColorGradientEnabled = true
        ///左侧的距离
        vi.contentEdgeInsetLeft = 22*scale
        ///单元格的间距
        vi.cellSpacing = 35*scale
        ///右侧的距离
        vi.contentEdgeInsetRight = 64*scale
        ///默认为NO。为YES时titleSelectedFont失效，以titleFont为准。
        //vi.isTitleLabelZoomEnabled = true
        //vi.titleLabelZoomScale = 1.4
        //vi.isTitleColorGradientEnabled = true
        vi.titleFont = kFont_PingFangSCRegular(14)
        vi.titleSelectedFont = kFont_PingFangSCSemibold(22)
        vi.titleLabelAnchorPointStyle = JXCategoryTitleLabelAnchorPointStyle.center
        ///lineView
        let lineView = JXCategoryIndicatorDotLineView()
        //lineView.indicatorLineWidth = 30*scale
        //lineView.lineScrollOffsetX = 0
        //lineView.lineStyle = JXCategoryIndicatorLineStyle.lengthen
        lineView.verticalMargin = 3
        lineView.dotSize = CGSize(width: 6, height: 4)
        lineView.dotLineViewColor = kColor_MDH333333()
        vi.indicators = [lineView]
        
        /////椭圆➕背景
        //let bv = JXCategoryIndicatorBackgroundView()
        //
        //bv.indicatorHeight = 20;
        //bv.indicatorCornerRadius = JXCategoryViewAutomaticDimension
        //bv.indicatorWidthIncrement = 10
        /////
        //bv.shadowColor = UIColor.red
        //bv.shadowRadius = 3
        //bv.shadowOffset = CGSize.init(width: 3, height: 4)
        //bv.shadowOpacity = 0.6
        //vi.indicators = [bv]
        
        /*let imageIndicator = MMCategoryIndicatorImageView()
        imageIndicator.indicatorImageView.image = UIImage(named_dh: "title_choose")
        imageIndicator.indicatorImageViewSize = CGSize(width: 32 * scale, height: 12 * scale)
        imageIndicator.verticalMargin = 6
        //imageIndicator.indicatorWidthIncrement = 15
        //imageIndicator.indicatorWidth = 10
        vi.indicators = [imageIndicator]*/
        return vi
    }
    
    ///第二层的Segment
    @objc class func viewCategorySecondTitle() -> JXCategoryTitleView {
        let scale = kMDHPTAutoScale()
        let vi = JXCategoryTitleView()
        vi.defaultSelectedIndex = 0
        vi.backgroundColor = UIColor.white
        vi.titleSelectedColor = kColor_MDH333333()
        vi.titleColor = kColor_MDHHex("#909090")
        ///不平分宽度
        vi.isAverageCellSpacingEnabled = false
        ///是否渐变过渡
        vi.isTitleColorGradientEnabled = true
        ///左侧的距离
        vi.contentEdgeInsetLeft = 20*scale
        ///单元格的间距
        vi.cellSpacing = 28*scale
        ///右侧的距离
        vi.contentEdgeInsetRight = vi.contentEdgeInsetLeft
        ///默认为NO。为YES时titleSelectedFont失效，以titleFont为准。
        //vi.isTitleLabelZoomEnabled = true
        //vi.titleLabelZoomScale = 1.4
        //vi.isTitleColorGradientEnabled = true
        vi.titleFont = kFont_PingFangSCRegular(12)
        vi.titleSelectedFont = kFont_PingFangSCRegular(12)
        vi.titleLabelAnchorPointStyle = JXCategoryTitleLabelAnchorPointStyle.center
        /*
        ///lineView
        let lineView = JXCategoryIndicatorLineView()
        lineView.indicatorLineWidth = 18*scale
        lineView.lineScrollOffsetX = 0
        lineView.lineStyle = JXCategoryIndicatorLineStyle.normal
        lineView.verticalMargin = 5
        lineView.indicatorColor = kColor_MDHHex("#7061FF")
        vi.indicators = [lineView]
        */
        ///椭圆➕背景
        let bv = JXCategoryIndicatorBackgroundView()
        bv.backgroundViewColor = kColor_MDHHex("#F3F3F3")
         bv.indicatorHeight = 28*scale
         bv.indicatorCornerRadius = JXCategoryViewAutomaticDimension
         bv.indicatorWidthIncrement = 24*scale
        /*///
         bv.shadowColor = UIColor.red
         bv.shadowRadius = 3
         bv.shadowOffset = CGSize.init(width: 3, height: 4)
         bv.shadowOpacity = 0.6*/
        vi.indicators = [bv]
        return vi
    }
    
    
    ///处理用户信息
    @objc class func userModel(user: MDHUserModel) -> () {
        
    }
    
    ///携带参数 进入APP -> 需要提示 进一步操作
    @objc class func show_openInstallData() -> () {
        
    }
    
    /**
     brief description：返回四个或者五个button均分一行的view
     params：
        viewArray:存放子view的数组
        viewSize:子view的尺寸
        leftMargin:距离返回页面左的距离
        rightMargin:距离返回试图右边的距离
        lineVerticalInterval:行与行之间的距离
        numberOfViewInOneLine:一共多少行
        viewWidth:返回页面的宽度,Note:这个参数没有 乘以autoscale，所以如果传screenWidth，不用修改;如果传具体尺寸，需要*autoscale
     */
    @objc class func getDividedView(viewArray: [UIView], viewSize: CGSize, leftMargin: CGFloat, rightMargin: CGFloat, lineVerticalInterval: CGFloat, numberOfViewInOneLine: Int, dividedViewWidth: CGFloat) -> UIView {
        if viewArray.count < 1 {
            return UIView()
        }
        
        if viewArray.count == 1 {
            let view = viewArray[0]
            view.frame = CGRect(x: 0, y: 0, width: viewSize.width * kMDHPTAutoScale(), height: viewSize.height * kMDHPTAutoScale())
            return view
        }
        
        let bgView = UIView()
        
        let viewWidth = viewSize.width * kMDHPTAutoScale()
        let viewHeight = viewSize.height * kMDHPTAutoScale()
        let viewCount = viewArray.count
        
        let leftMargin1 = leftMargin * kMDHPTAutoScale()
        let rightMargin1 = rightMargin * kMDHPTAutoScale()
        let lineVerticalInterval1 = lineVerticalInterval * kMDHPTAutoScale()
        
        let intervalTotalSpace = (dividedViewWidth - leftMargin1 - rightMargin1 - CGFloat(numberOfViewInOneLine) * viewWidth)
        let horizontalInterval = intervalTotalSpace / (CGFloat(numberOfViewInOneLine) - 1)//横向距离
        
        for i in 0..<viewCount {
            let view = viewArray[i]
            view.frame = CGRect(x: leftMargin1 + CGFloat(i % numberOfViewInOneLine) * (viewWidth + horizontalInterval), y: CGFloat(i / numberOfViewInOneLine) * (viewHeight + lineVerticalInterval1), width: viewWidth, height: viewHeight)
            bgView.addSubview(view)
        }
        let bgViewHeight = viewHeight + CGFloat((viewCount - 1) / numberOfViewInOneLine) * (viewHeight + lineVerticalInterval1)
        bgView.frame = CGRect(x: 0, y: 0, width: dividedViewWidth, height: bgViewHeight)
        
        return bgView
    }
    
    //MARK: - ==== 创建横向多个view视图
    /**
     brief description：返回四个或者五个button的view，根据button宽高和间隙，不确定view多长
     params：
        viewArray:存放子view的数组
        viewSize:子view的尺寸
        horizontalInterval:两个View之间的距离
     */
    @objc class func getDividedView2(viewArray: [UIView], viewSize: CGSize,horizontalInterval:CGFloat) -> UIView {
        if viewArray.count == 0 {
            return UIView()
        }
        
        if viewArray.count == 1 {
            let view = viewArray[0]
            view.mh_size = viewSize
            return view
        }
        
        let bgView = UIView()
        
        let viewWidth = viewSize.width
        let viewHeight = viewSize.height
        let viewCount = viewArray.count
        
        for i in 0..<viewCount {
            let view = viewArray[i]
            view.frame = CGRect(x: CGFloat(i) * (viewWidth + horizontalInterval), y: 0, width: viewWidth, height: viewHeight)
            bgView.addSubview(view)
        }
        bgView.frame = CGRect(x: 0, y: 0, width: CGFloat(viewCount) * viewWidth + CGFloat(viewCount - 1) * horizontalInterval, height: viewHeight)

        return bgView
    }
    
    ///实名认证 的 提示
    @objc class func showAlertVerified(skip: Bool = false, style: Int = 0) -> Bool {
        return true
    }
    
    //MARK: - ==== 跳转页面
    ///跳转播放视频的界面 播放视频的界面
    @objc class func playVideoVc(name: String, video: String, icon: String, image: UIImage?) -> () {
        
    }
    
    ///跳转搜索界面
    @objc class func pushSearchVc(index: Int = 0) -> () {
        
    }
    
    ///跳转到主页
    @objc class func pushPersonalHomeVc(user: MDHUserModel, index: Int = 0) -> () {
        
    }
    
    //MARK: - ==== 创建视图
    //APP的背景图
    @objc class func image_app_back(type: Int = 0) -> UIImage? {
        var ima_name = "back_app_8"
        if kMMWPTFC().is_IPHONE_5 {
            ima_name = "back_app_se"
        }else if kMMWPTFC().is_IPHONE_6 {
            ima_name = "back_app_8"
        }else if kMMWPTFC().is_IPHONE_6_PLUS {
            ima_name = "back_app_8p"
        }else if kMMWPTFC().is_IPHONE_X {
            switch kMDH_SCREEN_WIDTH() {
            case 375:
                ima_name = "back_app_xs"
                break
            case 414:
                ima_name = "back_app_xsmax"
                break
            default:
                break
            }
        }
        return UIImage(named: ima_name)
    }
    
    ///带有圆圈的 统一创建用户头像
    @objc class func imvUserHeadPic(width: CGFloat, radius: CGFloat = 8, isLine: Bool = false, lineColor: UIColor = kColor_MDHF2F2F2()) -> SDAnimatedImageView {
        ///需要取整一下
        //let wh1 = CGFloat(floor(width*kMDHPTAutoScale()))//wh1/2.0
        let imv = self.createImageView(size: CGSize(width: width, height: width), radius: radius, isLine: isLine, lineColor: lineColor)
        return imv
    }
    
    ///统一创建UIImageView
    @objc class func createImageView(size: CGSize, radius: CGFloat = 0, isLine: Bool = true, lineColor: UIColor = kColor_MDHF2F2F2()) -> SDAnimatedImageView {
        /* ceil(x)返回不小于x的最小整数值（然后转换为double型） floor(x)返回不大于x的最大整数值。 round(x)返回x的四舍五入整数值。  */
        let scale = kMDHPTAutoScale()
        ///需要取整一下
        let width1 = CGFloat(floor(size.width*scale))
        let height1 = CGFloat(floor(size.height*scale))
        let imv = SDAnimatedImageView(frame: CGRect.init(x: 0, y: 0, width: width1, height: height1))
        imv.image = MDHWebImagePlaceholder()
        imv.runLoopMode = RunLoop.Mode.common
        var radius1 = radius
        if radius1 == 8 {
            radius1 = height1/2.0
        }
        if radius1 <= 0 {
            radius1 = height1/2.0
        }
        self.mdh_l_cornerRadius(v: imv, radius: radius1, isLine: isLine, lineColor: lineColor)
        return imv
    }
    
    ///对视图添加一个 角度 结合UIBezierPath 与 CAShapeLayer 画图
    @objc class func mdh_l_cornerRadius(v: UIView, radius: CGFloat, isLine: Bool = true, lineColor: UIColor = kColor_MDHF2F2F2()) -> () {
        v.dh_cornerRadius = radius
        if isLine {
            v.borderColor = lineColor
            v.borderWidth = 1
        }
        /*///添加圆角 蒙版 线的路径
         let maskPathIuv = UIBezierPath.init(roundedRect: v.bounds, byRoundingCorners: UIRectCorner.allCorners, cornerRadii: CGSize.init(width: radius, height: radius))
         let maskLayerIuv = CAShapeLayer.init()
         maskLayerIuv.frame = v.bounds
         maskLayerIuv.path = maskPathIuv.cgPath
         v.layer.mask = maskLayerIuv
         
         if isLine {///设置圆角线 设置线
         let maskPathLine = UIBezierPath.init(roundedRect: v.bounds, cornerRadius: radius)
         let maskLayerLineIuv = CAShapeLayer.init()
         maskLayerLineIuv.frame = v.bounds
         maskLayerLineIuv.path = maskPathLine.cgPath
         maskLayerLineIuv.strokeColor = lineColor.cgColor
         maskLayerLineIuv.lineWidth = 1.0
         maskLayerLineIuv.fillColor = nil
         v.layer.addSublayer(maskLayerLineIuv)
         }*/
    }
    
    ///创建统一的按钮 类似登录按钮
    @objc class func createUnifiedButtonWhite(text: String, size: CGSize = CGSize.zero, radius: CGFloat = 5, isSlc: Bool = false) -> MDHButton {
        let buttonBuildLobby = MDHButton()
        let scale = kMDHPTAutoScale()
        if size == CGSize.zero {
            let btnHeight: CGFloat = 56*scale
            buttonBuildLobby.frame = CGRect(x: 0, y: 0, width: 325*scale, height: btnHeight)
        }else{
            buttonBuildLobby.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        }
        
        var name_ima = "loginRegister_button"
        if size.width/scale == 329 && size.height/scale == 46 {
            name_ima = "host_authentication_button_32946"
        }
        buttonBuildLobby.setBackgroundImage(UIImage(named: name_ima), for: UIControl.State.normal)
        buttonBuildLobby.setBackgroundImage(UIImage(color: kColor_MDHHex("#D8D8D8")), for: .disabled)
        buttonBuildLobby.setTitle(text, for: UIControl.State.normal)
        buttonBuildLobby.setTitleColor(kColor_MDHFFFFFF(), for: UIControl.State.normal)
        buttonBuildLobby.titleLabel?.font = kFont_PingFangSCRegular(18)
        var rad = radius
        rad = buttonBuildLobby.mh_height/2.0
        self.mdh_l_cornerRadius(v: buttonBuildLobby, radius: rad, isLine: false)
        return buttonBuildLobby
    }
    
    ///创建 验证码 的按钮
    @objc class func buttonVerificationCode(n_tit: String, size: CGSize = CGSize.zero) -> MDHButton {
        let scale = kMDHPTAutoScale()
        var b_size = CGSize(width: 98*scale, height: 34*scale)
        if size != CGSize.zero {
            b_size = size
        }
        let btn = MDHSwiftHeader.createUnifiedButtonWhite(text: n_tit, size: b_size, radius: b_size.height/2.0)
        btn.setBackgroundImage(UIImage(named: "host_authentication_button_32946"), for: .normal)
        btn.setBackgroundImage(UIImage(color: kColor_MDHHex("#EBEBEB")), for: .selected)
        btn.setTitle(n_tit, for: .normal)
        btn.setTitleColor(kColor_MDHFFFFFF(), for: .normal)
        btn.setTitleColor(kColor_MDHHex("#B8B8B8"), for: .selected)
        btn.titleLabel?.font = kFont_PingFangSCRegular(13)
        return btn
    }
    
    ///titleLabel创建，eg。账号登录
    @objc class func createCommonTitleLabel(titleString : String) -> UILabel {
        let label = UILabel()
        label.font = kFont_PingFangSCMedium(20)
        label.textColor = kColor_MDH333333()
        label.text = titleString
        return label
    }
    
    ///创建统一的 输入框 类似登录界面
    @objc class func createUnifiedTextField(placeholder: String) -> UITextField {
        let hSearch = 44
        let textFieldSous = UITextField.init(frame: CGRect.init(x: 0, y: 0, width: 200, height: hSearch))
        textFieldSous.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor : kColor_MDHHex("#D9D9D9"),NSAttributedString.Key.font : kFont_PingFangSCRegular(14)])
        textFieldSous.clearButtonMode = .always
        //textFieldSous.font = kFont_PingFangSCRegular(16)
        textFieldSous.borderStyle = .none
        textFieldSous.textColor = kColor_MDH333333()
        //textFieldSous.tintColor = kColor_MDH8976CA()
        textFieldSous.backgroundColor = UIColor.white.withAlphaComponent(0.0001)
        //textFieldSous.background = UIColor.image(with: UIColor.colorF3F3F3())
        //textFieldSous.becomeFirstResponder()
        //textFieldSous.layer.masksToBounds = true
        //textFieldSous.layer.cornerRadius  = 3
        return textFieldSous
    }
    
    ///当前的手机号码
    //var textPhone = ""
    ///监听 手机号 TextField 的录入
    @objc class func racPhoneTextSignal(tf: UITextField, countryCode: String) -> RACDisposable? {
        var phoneNumber = ""
        ///弱变量
        weak var weakTf = tf
        ///监听手机号的录入
        return weakTf?.rac_textSignal().filter { (value) -> Bool in
            if countryCode == "+86" {
                let length = (value?.length ?? 0)
                if phoneNumber.count < length {
                    if length == 4 || length == 9 {
                        let occString = value?.substring(from: length-1) ?? ""
                        let replaceString = String.init(format: " %@", occString);
                        weakTf?.text = (value?.substring(to: length-1) ?? "")+replaceString
                    }
                }else{
                    if length == 4 || length == 9 {
                        if length == (weakTf?.text?.count ?? 0) {
                            weakTf?.text = (value?.substring(to: length-1) ?? "")
                        }
                    }
                }
                phoneNumber = weakTf?.text ?? ""
                return length > 13
            }
            return true
        }.subscribeNext { (value) in
            if countryCode == "+86" {
                weakTf?.text = (value?.substring(to: 13) ?? "")
            }else{
                weakTf?.text = value as String?
            }
        }
    }
    
    ///创建密码的TextField
    @objc class func createPasswordTextField(placeholder: String = "请输入密码") -> UITextField {
        let tf = MDHSwiftHeader.createUnifiedTextField(placeholder: placeholder)
        tf.isSecureTextEntry = true
        tf.rightViewMode = .always
        
        let btn = MDHButton()
        tf.rightView = btn
        let scale = kMDHPTAutoScale()
        //btn.backgroundColor = UIColor.red
        btn.frame = CGRect.init(x: 0, y: 0, width: 36*scale, height: 36*scale)
        btn.setImage(UIImage(named: "loginRegister_hidden"), for: UIControl.State.normal)
        btn.setImage(UIImage(named: "loginRegister_according"), for: UIControl.State.selected)
        
        weak var weakTf = tf
        btn.rac_signal(for: .touchUpInside)
            .deliverOnMainThread().subscribeNext({ (x) in
            let sender = x as! MDHButton
            sender.isSelected = !sender.isSelected
            weakTf?.isSecureTextEntry = !sender.isSelected
        })
        return tf;
    }
    
    ///创建倒计时 时间
    @objc class func verCodeTimerSource(btn: MDHButton) -> DispatchSourceTimer? {
        if btn.isSelected {
            return nil
        }
        ///弱变量
        weak var weakBtn = btn
        // 定义需要计时的时间
        var timeCount = 60
        // 在global线程里创建一个时间源
        let codeTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
        // 设定这个时间源是每秒循环一次，立即开始
        codeTimer.schedule(deadline: DispatchTime.now(), repeating: 1)
        // 设定时间源的触发事件
        codeTimer.setEventHandler(handler: {
            MDHFileConstant.mainAsyncSafe {
                // 每秒计时一次
                timeCount = timeCount - 1
                // 时间到了取消时间源
                if timeCount <= 0 {
                    weakBtn?.isSelected = false
                    //weakBtn?.setBackgroundImage(UIImage(color: kColor_MDHHex("#EBEBEB")), for: .normal)
                    weakBtn?.setTitle("重新获取", for: UIControl.State.normal)
                    weakBtn?.isUserInteractionEnabled = true
                    //weakBtn?.setTitleColor(kColor_MDHFFFFFF(), for: UIControl.State.normal)
                    codeTimer.cancel()
                }else{
                    weakBtn?.isSelected = true
                    //weakBtn?.setBackgroundImage(UIImage(color: kColor_MDHHex("#EBEBEB")), for: .normal)
                    // 返回主线程处理一些事件，更新UI等等
                    weakBtn?.setTitle("重新获取(\(timeCount))", for: UIControl.State.selected)
                    //weakBtn?.setTitleColor(kColor_MDHHex("#B8B8B8"), for: UIControl.State.normal)
                    weakBtn?.isUserInteractionEnabled = false
                }
            }
        })
        return codeTimer
    }
    
    ///动态图标
    @objc class func getDynamicIconAtt(guildName: String, guild: String, official: String, level: String) -> NSAttributedString {
        ///富文本
        let attachText = NSMutableAttributedString()
        let scale = kMDHPTAutoScale()
        let font = kFont_PingFangSCRegular(12)
        let attSpace = " ".ck_attributeString()

        if !official.isEmpty {
            let officialImg = SDAnimatedImageView(frame: CGRect(x: 0, y: 0, width: 34 * scale, height: 16 * scale))
            officialImg.contentMode = UIView.ContentMode.scaleAspectFit
            officialImg.sd_setImage(with: URL.init(string: official), placeholderImage: MDHWebAvatarImagePlaceholder())
            let attachTextItem = NSMutableAttributedString.yy_attachmentString(withContent: officialImg, contentMode: UIView.ContentMode.center, attachmentSize: officialImg.bounds.size, alignTo: font, alignment: YYTextVerticalAlignment.center)
            attachText.append(attachTextItem)
            ///使得图片之间有间隔
            attachText.append(attSpace)
        }

        if !level.isEmpty {
            let levelImg = SDAnimatedImageView(frame: CGRect(x: 0, y: 0, width: 18 * scale, height: 18 * scale))
            levelImg.contentMode = UIView.ContentMode.scaleAspectFit
            levelImg.sd_setImage(with: URL.init(string: level), placeholderImage: MDHWebAvatarImagePlaceholder())
            let attachTextItem = NSMutableAttributedString.yy_attachmentString(withContent: levelImg, contentMode: UIView.ContentMode.center, attachmentSize: levelImg.bounds.size, alignTo: font, alignment: YYTextVerticalAlignment.center)
            attachText.append(attachTextItem)
            ///使得图片之间有间隔
            attachText.append(attSpace)
        }
        
        if !guildName.isEmpty && !guild.isEmpty {
            let guildImg = SDAnimatedImageView(frame: CGRect(x: 0, y: 0, width: 59 * scale, height: 18 * scale))
            guildImg.contentMode = UIView.ContentMode.scaleAspectFit
            guildImg.sd_setImage(with: URL.init(string: guild), placeholderImage: MDHWebAvatarImagePlaceholder())
            
            let guildLab = UILabel(frame: CGRect(x: 10 * scale, y: 4 * scale, width: 39 * scale, height: 14 * scale))
            guildImg.addSubview(guildLab)
            guildLab.text = guildName
            guildLab.textAlignment = .center
            guildLab.font = kFont_PingFangSCSemibold(9)
            guildLab.textColor = kColor_MDHFFFFFF()
            let attachTextItem = NSMutableAttributedString.yy_attachmentString(withContent: guildImg, contentMode: UIView.ContentMode.center, attachmentSize: guildImg.bounds.size, alignTo: font, alignment: YYTextVerticalAlignment.center)
            attachText.append(attachTextItem)
            /////使得图片之间有间隔
            //attachText.append(attSpace)
        }
        attachText.yy_font = font
        return attachText.ck_attributeString()
    }
    
    ///创建用户的 图标信息 Att
    @objc class func userInforIconAtt(nickname: String = "", nc_color: UIColor = UIColor.white, nc_font: UIFont = UIFont.systemFont(ofSize: 12), sex: Int = -1, icons_s: [String] = [], icons_m: [String] = [], sizeM: CGSize = CGSize.zero, sizeS: CGSize = CGSize.zero) -> NSAttributedString {
        ///富文本
        let attachText = NSMutableAttributedString()
        let scale = kMDHPTAutoScale()
        let font = nc_font
        let attJxKon = " ".ck_attributeString()
        ///等级 默认图标的图标
        let iconDefaultImage = MDHWebAvatarImagePlaceholder()
        ///等级图标的frame 大图标
        var frame_m = CGRect(x: 0, y: 0, width: 38*scale, height: 18*scale)
        if sizeM.width > 0 && sizeM.height > 0 {
            frame_m.size.width = sizeM.width*scale
            frame_m.size.height = sizeM.height*scale
        }
        ///官方 及 新人 小图标
        var frame_s = CGRect(x: 0, y: 0, width: 18*scale, height: 18*scale)
        if sizeS.width > 0 && sizeS.height > 0 {
            frame_s.size.width = sizeS.width*scale
            frame_s.size.height = sizeS.height*scale
        }
        ///昵称
        if nickname.count > 0 {
            let fromAttr = NSMutableAttributedString(string: nickname)
            fromAttr.yy_color = nc_color
            fromAttr.yy_font = nc_font
            attachText.append(fromAttr)
            ///使得图片之间有间隔
            attachText.append(attJxKon)
        }
        ///性别
        if sex != -1 {
            let imv_xb = MDHSexImageView()
            imv_xb.mh_size = CGSize(width: 20*scale, height: 20*scale)
            imv_xb.sex = sex
            let attachTextLevel = NSMutableAttributedString.yy_attachmentString(withContent: imv_xb, contentMode: UIView.ContentMode.center, attachmentSize: imv_xb.mh_size, alignTo: font, alignment: YYTextVerticalAlignment.center)
            attachText.append(attachTextLevel)
            ///使得图片之间有间隔
            attachText.append(attJxKon)
        }
        
        ///大图标的视图
        for icon in icons_m {
            if icon.count > 0 {
                let iconImv = SDAnimatedImageView(frame: frame_m)
                iconImv.contentMode = UIView.ContentMode.scaleAspectFit
                if icon.hasPrefix("http") {
                    iconImv.sd_setImage(with: URL.init(string: icon), placeholderImage: iconDefaultImage)
                }else{
                    iconImv.image = UIImage(named: icon)
                }
                ///等级
                let attachTextLevel = NSMutableAttributedString.yy_attachmentString(withContent: iconImv, contentMode: UIView.ContentMode.center, attachmentSize: frame_m.size, alignTo: font, alignment: YYTextVerticalAlignment.center)
                attachText.append(attachTextLevel)
                ///使得图片之间有间隔
                attachText.append(attJxKon)
            }
        }
        
        ///小图标的视图
        for icon in icons_s {
            if icon.count > 0 {
                let iconImv = SDAnimatedImageView(frame: frame_s)
                iconImv.contentMode = UIView.ContentMode.scaleAspectFit
                if icon.hasPrefix("http") {
                    iconImv.sd_setImage(with: URL.init(string: icon), placeholderImage: iconDefaultImage)
                }else{
                    iconImv.image = UIImage(named: icon)
                }
                ///等级
                let attachTextLevel = NSMutableAttributedString.yy_attachmentString(withContent: iconImv, contentMode: UIView.ContentMode.center, attachmentSize: frame_s.size, alignTo: font, alignment: YYTextVerticalAlignment.center)
                attachText.append(attachTextLevel)
                ///使得图片之间有间隔
                attachText.append(attJxKon)
            }
        }
        attachText.yy_font = font
        return attachText.ck_attributeString()
    }
    
    ///创建用户的 图标信息
    @objc class func userInforIcon(nickname: String = "", nc_color: UIColor = UIColor.white, nc_font: UIFont = UIFont.systemFont(ofSize: 12), sex: Int = -1, icons_s: [String] = [], icons_m: [String] = [], sizeM: CGSize = CGSize.zero, sizeS: CGSize = CGSize.zero) -> YYTextLayout? {
        let scale = kMDHPTAutoScale()
        let attachText = MDHSwiftHeader.userInforIconAtt(nickname: nickname, nc_color: nc_color, nc_font: nc_font, sex: sex, icons_s: icons_s, icons_m: icons_m, sizeM: sizeM, sizeS: sizeS)
        /// 实现布局好宽高 以及属性
        /// PS:用这个方法计算尺寸 要比 [self.textAttr mh_sizeWithLimitWidth:limitWidth]这个计算的值要准确的多
        let container_nr = YYTextContainer(size: CGSize(width: 400*scale, height: 20*scale))
        container_nr.maximumNumberOfRows = 1
        container_nr.truncationType = .middle
        let layout_nr = YYTextLayout(container: container_nr, text: attachText)
        //let fcl_w = layout_nr?.textBoundingSize.width ?? 0
        //let fcl_h = layout_nr?.textBoundingSize.height ?? 0
        //item.frameContentLabel = CGRect(x: 67*scale, y: 36.5*scale, width: fcl_w+2, height: fcl_h+2)
        return layout_nr//attachText.ck_attributeString()
    }
    
    //创建含表情的富文本
    @objc class func createFaceAttributeWithContent(content: String, font: UIFont, color: UIColor) -> NSMutableAttributedString {
        let text = (content as NSString).emojiTransiOSAndroid(false) ?? content
        let attr = NSMutableAttributedString(string: text)
        attr.yy_font = font
        attr.yy_color = color
        attr.mh_regexContentWith(withEmojiImageFontSize: font.pointSize * kMDHPTAutoScale())
        return attr
    }
    
    //YYlabel的文本size
    @objc class func getHeightWithContent(content: NSAttributedString, size: CGSize) -> CGSize {
        let layout = YYTextLayout.init(containerSize: size, text: content)
        return layout?.textBoundingSize ?? CGSize.zero
    }
    
    ///毫秒 转 天时分秒 字符串
    @objc class func getTimeStringWithSeconds(seconds: Int) -> String {
        let second = seconds % 60
        let minute = (seconds % 3600)/60
        let hour = (seconds % (24 * 3600))/3600
        let day = seconds / (24 * 3600)
        
        var time = ""
        if day == 0 && hour == 0 {
            time =  String(format: "%02d分%02d秒", minute, second)
        }else if day == 0 && hour > 0 {
            time =  String(format: "%02d时%02d分%02d秒", hour, minute, second)
        }else {
            time =  String(format: "%02d天%02d时%02d分%02d秒", day, hour, minute, second)
        }
        return time
    }
    
    
    //MARK: - ==== 第三方库 相关
    
    //MARK: - === 获取缓存 YYCache
    @objc class func getCache() -> String {
        var cacheSize: CGFloat = 0.0
        cacheSize += CGFloat(MHFileManager.folderSize(atPath: MHWeChatCacheDirPath()))
        cacheSize += CGFloat(SDImageCache.shared.diskCache.totalSize())
        ///录音文件
        //cacheSize += CGFloat(MHFileManager.folderSize(atPath: CWFlieManager.cwFolderPath()))
        return String.init(format: "%0.2f MB", cacheSize/1000/1000)
    }
    
    ///清理缓存
    @objc class func clearCache(block: VoidBlock?) -> () {
        MHFileManager.removeFile(MHWeChatCacheDirPath())
        SDImageCache.shared.diskCache.removeAllData()
        if block != nil {
            block!()
        }
        ///录音文件
        //CWFlieManager.removeFile(CWFlieManager.cwFolderPath())
    }
    
    ///保存缓存数据 YYCache
    @objc class func save_cache(data: String, key: String) -> () {
        if key.count > 0 {
            MHFileManager.setHttpCache(data, url: key, parameters: nil)
        }
    }
    
    ///获取缓存数据 YYCache
    @objc class func get_cache(key: String) -> String {
        var data = ""
        if key.count > 0 {
            let shuju = MHFileManager.httpCache(forURL: key, parameters: nil) as? String ?? ""
            data = shuju
        }
        return data
    }
    
    ///数组类型的 MDHPTModel 转成字符串
    @objc class func save_cache(datas: Any, key: String) -> () {
        if key.count <= 0 {
            return
        }
        var data = ""
        if datas is [MDHPTModel] {///数组
            let datas_1 = datas as? [MDHPTModel] ?? [MDHPTModel]()
            if datas_1.count <= 0 {
                return
            }
            var data_str = [String]()
            for item in datas_1 {
                let str = item.mj_JSONString() ?? ""
                data_str.append(str)
            }
            data = (data_str as NSArray).mj_JSONString() ?? ""
        }else if datas is MDHPTModel {///单个Model
            let item = datas as? MDHPTModel ?? MDHPTModel()
            data = item.mj_JSONString() ?? ""
        }
        MDHSwiftHeader.save_cache(data: data, key: key)
    }
    
    /// 获取服务器的时间戳
    @objc class func server_timestamp() -> Int {
        let diff = MDHRouter.sharedInstance().services.client.diffTimeNetLoc
        let cur_time = (diff+Date().timeIntervalSince1970)
        return Int(cur_time*1000)
    }
    
    /// 6. 判断是否是数字
    ///
    /// - Parameter string: 传入的字符串
    /// - Returns: YES:是存数字 NO:不是
    @objc class func ValidateisPurnInt(string: String, length: Int = 0) -> Bool {
        let scan: Scanner = Scanner(string: string)
        var val:Int = 0
        return scan.scanInt(&val) && scan.isAtEnd
        /*var isOk = false
        if length == 0 || string.count == length {
            // 判断长度大于8位后再接着判断是否同时包含数字和字符
            let regex = "[0-9]"
            let pred = NSPredicate(format: "SELF MATCHES %@", regex)
            isOk = pred.evaluate(with: string)
        }
        return isOk*/
    }
    
    /*
     判断用户输入的密码 6-20位 是否符合规范，符合规范的密码要求：
     1. 长度大于5位
     2. 密码中必须同时包含数字和字母
     */
    @objc class func judgePasswordLegal(string: String) -> Bool {
        var isOk = false
        if string.count > 5 {
            // 判断长度大于8位后再接着判断是否同时包含数字和字符
            let regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$"
            let pred = NSPredicate(format: "SELF MATCHES %@", regex)
            isOk = pred.evaluate(with: string)
        }
        return isOk
    }
    
    //MARK: - ===== 加密
    /// 接口进行加密
    /// 将 字段进行 是否进行排序 返回 排序后的字符串
    @objc class func stringSort(dict: [String: Any], isSort: Bool = true) -> String {
        if !isSort {
            let json = (dict as NSDictionary).mj_JSONString() ?? ""
            return json
        }
        ///所有的参数 key值按照自然排序从大到小排序 a-z
        var allKeys = (dict as NSDictionary).allKeys as? [String] ?? [String]()
        if isSort {
            allKeys = allKeys.sorted(by: { (obj1, obj2) -> Bool in
                ///NSOrderedSame相同 NSOrderedAscending从大到小 NSOrderedDescending从小到大
                let re = obj1.compare(obj2)
                return re == .orderedAscending
            })
        }
        //最终的字符串
        var sb = ""
        ///将排序后的参数数组按照key=val&key=val的形式组成字符串
        for key in allKeys {
            var va = ""
            let value = dict[key]
            if value is String {
                va = value as? String ?? ""
            }else if value is NSNumber {
                va = (value as? NSNumber)?.stringValue ?? ""
            }else{
                va = value as? String ?? ""
            }
            sb += String(format: "%@=%@&", key, va)
        }
        if sb.count > 0 {
            sb.removeLast()
        }
        return sb
    }
    
    ///对字符串 进行加密
    @objc class func stringAES128ECB(data: String, key: String, iv: String) -> String {
        var hexkey = (key as NSString).md5() ?? ""
        if data.isEmpty || key.isEmpty || iv.isEmpty || hexkey.isEmpty {
            #if DEBUG
            ShowHUDMesHidden("字符串加密时出错，请查看MDHSwiftExtension", nil)
            #endif
            return data
        }
        hexkey = (hexkey as NSString).substring(with: NSRange(location: 8, length: 16))
        ///AES-128-ECB
        let result = CocoaSecurity.aesEncrypt(data, hexKey: hexkey, hexIv: iv)
        var server_sign = result?.base64 ?? ""
        ///之后base64
        server_sign = (server_sign as NSString).base64Encoded() ?? ""
        server_sign = self.stringReplaceCharacter(data: server_sign, fan: false)
        return server_sign
    }
    
    /// 将 "-", "_", "*" 替换成 "+", "/", "="
    @objc class func stringReplaceCharacter(data: String, fan: Bool) -> String {
        if data.isEmpty {
            return data
        }
        let huans = ["-", "_", "*"]
        let huans1 = ["+", "/", "="]
        var key = data
        for (i, zf) in huans.enumerated() {
            if fan {
                key = (key as NSString).replacingOccurrences(of: zf, with: huans1[i])
            }else{
                key = (key as NSString).replacingOccurrences(of: huans1[i], with: zf)
            }
        }
        return key
    }
    
    ///对加密的字符串进行解密
    @objc class func stringDecrypt(da: String, key: String, iv: String, isRe: Bool = true) -> String {
        var data = da
        var hexkey = (key as NSString).md5() ?? ""
        if data.isEmpty || key.isEmpty || iv.isEmpty || hexkey.isEmpty {
            #if DEBUG
            ShowHUDMesHidden("字符串解密时出错，请查看MDHSwiftExtension", nil)
            #endif
            return data
        }
        ///替换字符串
        if isRe {
            data = self.stringReplaceCharacter(data: data, fan: true)
        }
        data = (data as NSString).base64Decoded() ?? ""
        data = (data as NSString).replacingOccurrences(of: "\n", with: "")
        data = (data as NSString).replacingOccurrences(of: "\r", with: "")

        ///进行解密
        hexkey = (hexkey as NSString).substring(with: NSRange(location: 8, length: 16))
        let result = CocoaSecurity.aesDecrypt(withBase64: data, hexKey: hexkey, hexIv: iv)
        data = result?.base64 ?? ""
        data = (data as NSString).base64Decoded() ?? ""
        return data
    }
    
    ///对user_id进行加密
    @objc class func userIdEncrypt(uid: Int = 0) -> String {
        return "\(uid)"
    }
    
    ///H5网址 广告视图的时候跳转所用
    @objc class func urlWKWeb(url: String) -> String {
        if url.isEmpty {
            return url
        }
        var urlStr: String = url
        var userid = self.userIdEncrypt()
        if userid.isEmpty {
            userid = ""
        }
        urlStr += "?user_id=\(userid)&source=ios"
        return urlStr
    }
    
    ///对字符串进行加密
    @objc class func strinEncrypt(str: String) -> String {
        var userId: String = ""
        let user_id = str
        let user_id_data = user_id.data(using: String.Encoding.utf8)
        let user_id_base64 = user_id_data?.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
        if user_id_base64 == nil {
            return userId
        }
        userId = user_id_base64!.substring(to: user_id_base64!.index(user_id_base64!.startIndex, offsetBy: 2))+user_id
        if userId.isEmpty {
            return userId
        }
        let encrypt_key = "12345"
        let decrypt_key: NSString = "12345"
        var enstr = ""
        for itemI in userId {
            let itemIstr = String.init(itemI)
            var j = 1
            for itemJ in encrypt_key {
                let itemJstr = String.init(itemJ)
                if itemIstr == itemJstr {
                    enstr += decrypt_key.substring(with: NSRange.init(location: j-1, length: 1))
                    break
                }
                j += 1
            }
        }
        return enstr
    }
    
    ///8.0MARK: - 根据字数获取大小
    @objc class func getSizeWithFontAndText(font: UIFont, text: String, maxSize: CGSize) -> CGSize {
        let dic = NSDictionary(object: font, forKey: NSAttributedString.Key.font as NSCopying)
        return text.boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedString.Key : Any], context:nil).size
    }
    
    //MARK: - ==== 动态的高度
    ///视频的显示视图
    @objc class func createVideoBackImv() -> SDAnimatedImageView {
        let imv = SDAnimatedImageView()
        imv.dh_cornerRadius = 1
        imv.backgroundColor = MDHSwiftHeader.randomVideoBackColor()
        imv.contentMode = UIView.ContentMode.scaleAspectFill
        //imv.runLoopMode = RunLoop.Mode.common.rawValue
        return imv
    }
    ///随机 视频的 背景颜色
    @objc class func randomVideoBackColor() -> UIColor {
        let colors = [kColor_MDHTheme(),
                      UIColor.init(rgb: 0xd4237a),
                      UIColor.init(rgb: 0x9835ed),
                      UIColor.init(rgb: 0xdb639b),
                      UIColor.init(rgb: 0xe0620d)]
        let index = Int(arc4random()%UInt32(colors.count))
        return colors[index]
    }
}

//MARK: - ====== 字符串的扩展 ===== -
public protocol CKAlertViewStringable {
    
    func ck_string() -> String
    
    func ck_attributeString() -> NSAttributedString
    
    func ck_apply(align : NSTextAlignment) -> NSAttributedString
    
    func ck_apply(font :UIFont) -> NSAttributedString
    
    func ck_apply(color :UIColor) -> NSAttributedString
    
    func ck_apply(indent :CGFloat , style :CKIndentStyle) -> NSAttributedString
    
    func ck_apply(lineSpacing :CGFloat) -> NSAttributedString
}

extension String : CKAlertViewStringable {
    
    public func ck_string() -> String {
        return self
    }
    
    /// 简单的给文字赋予颜色
    ///
    /// - parameter color: 颜色
    ///
    /// - returns: NSMutableAttributedString
    public func ck_attributeString() -> NSAttributedString {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 3.0
        paragraphStyle.alignment = .left
        
        let attrString = NSMutableAttributedString(string: self)
        attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, attrString.length))
        
        return attrString
    }
    
    public func ck_apply(align : NSTextAlignment) -> NSAttributedString {
        return ck_attributeString().ck_apply(align: align)
    }
    
    public func ck_apply(font :UIFont) -> NSAttributedString {
        return ck_attributeString().ck_apply(font: font)
    }
    
    public func ck_apply(color :UIColor) -> NSAttributedString {
        return ck_attributeString().ck_apply(color: color)
    }
    
    public func ck_apply(indent :CGFloat , style :CKIndentStyle) -> NSAttributedString {
        return ck_attributeString().ck_apply(indent: indent, style: style)
    }
    
    public func ck_apply(lineSpacing :CGFloat) -> NSAttributedString {
        return ck_attributeString().ck_apply(lineSpacing:lineSpacing)
    }
}

public enum CKIndentStyle {
    case firstLine , headIndent , tailIndent
}

extension NSAttributedString : CKAlertViewStringable {
    
    public func ck_string() -> String {
        return string
    }
    
    public func ck_attributeString() -> NSAttributedString {
        return self
    }
    
    public func ck_apply(align : NSTextAlignment) -> NSAttributedString {
        
        let finalAttributes = self.attributes(at: 0, effectiveRange: nil)
        if let paragraphStyle = finalAttributes[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle {
            paragraphStyle.alignment = align
        }
        
        return self
    }
    
    public func ck_apply(font :UIFont) -> NSAttributedString {
        let finalString :NSMutableAttributedString = NSMutableAttributedString(attributedString: self)
        finalString.addAttribute(NSAttributedString.Key.font, value: font, range: NSMakeRange(0, length))
        return finalString
    }
    
    public func ck_apply(color :UIColor) -> NSAttributedString {
        let finalString :NSMutableAttributedString = NSMutableAttributedString(attributedString: self)
        finalString.addAttribute(NSAttributedString.Key.foregroundColor, value:color, range:NSMakeRange(0, length));
        return finalString
    }
    
    public func ck_apply(indent :CGFloat , style :CKIndentStyle) -> NSAttributedString {
        let finalAttributes = self.attributes(at: 0, effectiveRange: nil)
        if let paragraphStyle = finalAttributes[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle {
            switch style {
            case .firstLine:
                paragraphStyle.firstLineHeadIndent = indent
            case .headIndent:
                paragraphStyle.headIndent = indent
            case .tailIndent:
                paragraphStyle.tailIndent = indent
            }
        }
        
        return self
    }
    
    public func ck_apply(lineSpacing :CGFloat) -> NSAttributedString {
        let finalAttributes = self.attributes(at: 0, effectiveRange: nil)
        if let paragraphStyle = finalAttributes[NSAttributedString.Key.paragraphStyle] as? NSMutableParagraphStyle {
            paragraphStyle.lineSpacing = lineSpacing
        }
        return self
    }
}

